package services

import (
	"context"
	"k8sdev/pkg/client"
	"log"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

func GetNodes() (nodeList *[]v1.Node, err error) {
	err = client.NewClient()
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	client := client.GetDynamicClient()
	gvr := schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "nodes",
	}
	unStructured, err := client.Resource(gvr).List(context.Background(), metav1.ListOptions{})
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	unStructuredMap := unStructured.UnstructuredContent()
	coreV1nodeList := &v1.NodeList{}
	err = runtime.DefaultUnstructuredConverter.FromUnstructured(unStructuredMap, coreV1nodeList)
	if err != nil {
		log.Fatal(err.Error())
		return
	}

	nodeList = &coreV1nodeList.Items

	return
}
